/**
 * CoffeeMilk (C) 2010 Amen Hamdan
 * 
 * See the NOTICE file distributed with this work for additional 
 * information regarding copyright ownership.  This file is licenses
 * to you under the Apache License, Version 2.0 (the "License"); you 
 * may not use this file except in compliance with the License.  You 
 * may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *     
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 
 * implied. See the License for the specific language governing 
 * permissions and limitations under the License.    
 * 
 */
package ameen.rtm.lib.request;

import java.net.URL;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;

import ameen.rtm.lib.RtmException;
import ameen.rtm.lib.RtmService.AccessPermission;


public class RtmRequestHandler {
	public static String fApiKey 			= null;
	public static String fSharedSecret 		= null;
	public static String milkUrl 			= "http://api.rememberthemilk.com/services/rest/?";
	public static String milkAuthUrl 		= "http://www.rememberthemilk.com/services/auth/?";

	public RtmRequestHandler(String apiKey, String sharedSecret) {
		fApiKey = apiKey;
		fSharedSecret = sharedSecret;
	}

	public synchronized JsonNode rtmCall(RtmRequestParameters requestParameters) throws RtmException {
		URL targetUrl;
		try {
			RtmRequestParameterHelper paramHelper = new RtmRequestParameterHelper(fApiKey, fSharedSecret, requestParameters);
			targetUrl = new URL(milkUrl + paramHelper.getRtmRequestString());
			JsonParser jsonParser = (new JsonFactory()).createJsonParser(targetUrl.openStream());
			JsonNode rootNode = (new ObjectMapper()).readTree(jsonParser).get("rsp");
		
			checkError(rootNode);
			return rootNode;
		
		} catch (RtmException rtme) {
			throw rtme;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private void checkError(JsonNode jsonNode) throws RtmException {
		RtmException rtmException = RtmException.createRtmException(jsonNode);
		if(rtmException != null) throw rtmException;
	}
	
	public synchronized String createAuthUrl(String frob, AccessPermission accessPerms) {
		RtmRequestParameters requestParameters = new RtmRequestParameters();
		requestParameters.put("perms", accessPerms.toString());
		requestParameters.put("frob", frob);
		RtmRequestParameterHelper paramHelper = new RtmRequestParameterHelper(fApiKey, fSharedSecret, requestParameters);
		return milkAuthUrl + paramHelper.getRtmRequestString();
	}
}
